<template>
  <div class="p-3 flex">
    <div class="w-full" :style="{ width: secondOpen ? '35%' : '100%' }">
      <div class="grid-content bg-purple">
        <Forms ref="subForm" :auto-query="true" :data-from="formData" :list="tabsList[0].pageSetting.search" name="userAuthorization" />
        <Table
          :btn-fix="btnFix"
          :column-list="tablesColumn"
          :get-height="tableHeight"
          name="userAuthorization"
          :style="{ height: `${tableHeight}px` }"
          :tables="mainTable"
        />
      </div>
    </div>
    <div class="relative w-0" style="margin-left: 0.5rem" :style="{ display: secondOpen ? 'block' : 'none', width: secondOpen ? '65%' : '' }">
      <el-form ref="assistantForm" class="demo-form-inline" :inline="true" :model="ChoiceObj">
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.用户账号')">
          <el-input v-model="ChoiceObj.USER_ID" disabled size="small" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.用户名称')">
          <el-input v-model="ChoiceObj.USER_NAME" disabled size="small" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.创建人员')">
          <el-input v-model="ChoiceObj.ADDWHO" disabled size="small" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.创建时间')">
          <el-input v-model="ChoiceObj.ADDTIME" disabled size="small" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.更新人员')">
          <el-input v-model="ChoiceObj.EDITWHO" disabled size="small" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.更新时间')">
          <el-input v-model="ChoiceObj.EDITTIME" disabled size="small" />
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" type="border-card" @tab-click="clickChange">
        <el-tab-pane v-for="(v, index) in tabsList" :key="index" :label="v.label" :name="v.name">
          <el-button style="margin-bottom: 15px" type="primary" @click="newAdd()">{{ translateTitle('Dams.ApplicationInterface.新增') }}</el-button>
          <Table
            v-loading="rightLodaing"
            :btn-fix="true"
            :column-list="v.mainTableColumn"
            :get-height="assistantHeight"
            :name="v.childrenTab.name"
            :style="{ height: `${assistantHeight}px` }"
            :tables="v.childrenTab"
          />
        </el-tab-pane>
      </el-tabs>
      <vui-icon class="absolute cursor-pointer" icon="close-circle-line" style="top: 0; right: 10px" @click="backTab" />
    </div>
    <el-dialog v-if="newAddDialog" v-model="newAddDialog" :title="translateTitle('Dams.ApplicationInterface.新增')" width="80%">
      <el-form v-if="tabsIndex == 1 || tabsIndex == 2 || tabsIndex == 3" ref="form" label-width="80px" :model="form">
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.组织机构')">
          <el-select v-model="form.ORG_ID" filterable :placeholder="translateTitle('Dams.ApplicationInterface.请选择')" @change="orgChange">
            <el-option v-for="item in organizationOptions" :key="item.ORG_ID" :label="item.NAME" :value="item.ORG_ID" />
          </el-select>
        </el-form-item>
        <el-form-item :label="labelName">
          <el-cascader v-if="tabsIndex == 3" v-model="form.code" :options="orgOptions" :props="props" @change="cascaderChange" />
          <el-select v-else v-model="form.code" filterable multiple :placeholder="translateTitle('Dams.ApplicationInterface.请选择')">
            <el-option v-for="item in orgOptions" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-select v-else v-model="newRole" filterable :placeholder="translateTitle('Dams.ApplicationInterface.请选择')">
        <el-option v-for="item in roleOptions" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
      <div class="text-center">
        <el-button @click="confirmNewAdd">{{ translateTitle('Dams.ApplicationInterface.确定') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import { GFCD } from '@/utils/utils'
  import debounce from 'lodash/debounce'
  import Table from './table.vue'
  import { getList } from '../api/home'
  import Forms from './forms'
  import { translateTitle } from '@/utils/i18n'
  export default {
    name: 'UserCorrelation',
    components: { Table, Forms },
    mixins: [Mixin],
    props: {
      tableTopList: {
        type: Array,
        default: () => [],
      },
      tablesColumn: {
        type: Array,
        default: () => [],
      },
      btnFix: {
        type: Boolean,
        default: false,
      },
      subSystem: {
        type: String,
        default: 'DAMS',
      },
      pageName: {
        type: String,
        default: '',
      },
      tables: {
        type: Object,
        default: () => {},
      },
      getAuthorizationMethod: {
        type: Object,
        default: () => {},
      },
      optionMethod: {
        type: String,
        default: '',
      },
      authorizationList: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        formData: {},
        userForm: {},
        newAddDialog: false,
        clientHeight: 0,
        mainTableColumn: [],
        url: '',
        dialogOptions: [],
        newRole: '',
        ChoiceObj: {},
        rightLodaing: false,
        unsubs: [],
        getChildrenTab: [],
        form: {},
        organizationOptions: [],
        orgOptions: [],
        cascaderRrops: {
          // lazy: true,
          // lazyLoad: this.getFirstLevel,
          value: 'BUSINESS_TYPE',
          label: 'BUSINESS_TYPEDESCRC',
          multiple: true,
        },
        tabsList: [],
        activeName: '',
        tabsIndex: 0,
        pageSetting: {},
        mainTable: {},
        subForm: {},
        secondOpen: false,
        tableHeight: '0',
        assistantHeight: '0',
      }
    },
    computed: {
      getHeight() {
        console.log(this.$refs['subForm']?.$el?.clientHeight)
        return `${this.clientHeight - 40 - 20 - 12 - 20 - this.$refs['subForm']?.$el?.clientHeight}`
      },
      assistant() {
        console.log(this.$refs['assistantForm']?.$el?.clientHeight)
        return `${this.clientHeight - this.$refs['assistantForm']?.$el?.clientHeight - 121 - 100}`
      },
      labelName() {
        let name = ''
        if (this.tabsIndex == 1) {
          name = translateTitle('Dams.ApplicationInterface.仓库')
        } else if (this.tabsIndex == 2) {
          name = translateTitle('Dams.ApplicationInterface.货主')
        } else if (this.tabsIndex == 3) {
          name = translateTitle('Dams.ApplicationInterface.单据')
        }
        return name
      },
    },
    watch: {
      tables: {
        deep: true,
        handler(newval) {
          this.mainTable = newval
        },
      },
      getHeight(val) {
        this.tableHeight = val
      },
      assistant(val) {
        this.assistantHeight = val
      },
      secondOpen(val) {
        console.log(val, this.$refs['assistantForm']?.$el?.clientHeight)
        this.$nextTick(() => {
          console.log(this.$refs['assistantForm']?.$el?.clientHeight)
          this.tableHeight = `${this.clientHeight - 40 - 20 - 12 - 20 - this.$refs['subForm']?.$el?.clientHeight}`
          this.assistantHeight = `${this.clientHeight - this.$refs['assistantForm']?.$el?.clientHeight - 121 - 100}`
          // this.assistantHeight = `${this.clientHeight - 247 - 100}`
        })
      },
    },
    created() {
      this.init()
    },
    methods: {
      translateTitle,
      cascaderChange(e) {
        console.log(e)
      },
      backTab() {
        this.secondOpen = false
        this.tabsIndex = 0
        this.activeName = this.tabsList[0].name
      },
      clickChange(item) {
        console.log(item.index)
        this.tabsIndex = item.index
        this.query({ USER_ID: this.ChoiceObj.USER_ID }, this.tabsList[this.tabsIndex].pageSetting.children.search.form.method)
      },
      // async getFirstLevel(node, resolve) {
      //   const { level, data } = node
      //   if (this.form.ORG_ID && level == 1) {
      //     let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
      //       data: JSON.stringify({
      //         '#LIMIT#': 1,
      //         '#PAGE_SIZE#': 9999,
      //         USER_ID: this.ChoiceObj.USER_ID,
      //         BUSINESS_TYPE: data.BUSINESS_TYPE,
      //         ORG_ID: this.form.ORG_ID,
      //       }),
      //       method: 'wms.orderType.query',
      //     })
      //     console.log(res)
      //     let list = res.data['wms.orderType.query'].data
      //     if (list.length == 0) {
      //       data.disabled = true
      //     } else {
      //       list.forEach((row) => {
      //         row.leaf = true
      //         row.BUSINESS_TYPE = row.ORDER_TYPE
      //         row.BUSINESS_TYPEDESCRC = row.ORDER_TYPEDESCRE
      //         // row.ORDER_TYPEDESCRE = true
      //       })
      //     }
      //     resolve(list)
      //   }
      // },
      getCascaderLevel() {
        let promises = this.orgOptions.map((el) => {
          return getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
            data: JSON.stringify({
              '#LIMIT#': 1,
              '#PAGE_SIZE#': 9999,
              USER_ID: this.ChoiceObj.USER_ID,
              BUSINESS_TYPE: el.BUSINESS_TYPE,
              ORG_ID: this.form.ORG_ID,
            }),
            method: 'wms.orderType.query',
          })
        })
        Promise.all(promises).then((posts) => {
          this.orgOptions.forEach((row, i) => {
            row.children = posts[i].data['wms.orderType.query'].data
            row.children.forEach((r) => {
              r.leaf = true
              r.BUSINESS_TYPE = r.ORDER_TYPE
              r.BUSINESS_TYPEDESCRC = r.ORDER_TYPEDESCRE
            })
            if (row.children.length == 0) {
              row.disabled = true
            }
          })
        })
      },
      async orgChange(e) {
        let method = ''
        let obj = { ORG_ID: e }
        if (this.tabsIndex == 1) {
          method = this.getAuthorizationMethod.warehouse
          obj.USER_ID = this.ChoiceObj.USER_ID
        } else if (this.tabsIndex == 2) {
          method = this.getAuthorizationMethod.owner
          obj.USER_ID = this.ChoiceObj.USER_ID
        } else if (this.tabsIndex == 3) {
          method = this.getAuthorizationMethod.businessOrder
        }
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999, ...obj }),
          method: method,
        })
        this.orgOptions = res.data[method].data
        if (this.tabsIndex == 1) {
          this.orgOptions.forEach((row) => {
            row.id = row.WAREHOUSE_ID
            row.label = row.DESCRC
          })
        } else if (this.tabsIndex == 2) {
          this.orgOptions.forEach((row) => {
            row.id = row.OWNER_ID
            row.label = row.DESCRC
          })
        } else {
          this.getCascaderLevel()
        }
      },
      common_event(event_name) {
        this[event_name]()
      },
      newAdd() {
        if (Object.keys(this.ChoiceObj).length == 0) return this.$baseMessage(translateTitle('Dams.ApplicationInterface.请选择用户'), 'error')
        this.newAddDialog = true
        this.newRole = ''
        this.form = {}
        console.log(this.form)
      },
      setCascaderParam(userId, orgId) {
        let newArr = []
        console.log(this.form.code)
        this.form.code.forEach((row) => {
          for (const key in row) {
            if (Object.hasOwnProperty.call(row, key)) {
              if (key == 1) {
                newArr.push({
                  USER_ID: userId,
                  ORDER_BUSINESS_TYPE: row[0],
                  ORDER_TYPE: row[1],
                  ORG_ID: orgId,
                })
              }
            }
          }
        })
        return newArr
      },
      setSelectParam(obj, key) {
        let newArr = []
        this.form.code.forEach((row) => {
          newArr.push({
            [key]: row,
            ...obj,
          })
        })
        return newArr
      },
      confirmNewAdd() {
        if (!this.ChoiceObj.ID) {
          this.$message({
            message: translateTitle('Dams.ApplicationInterface.请选择用户'),
            type: 'warning',
          })
          return
        }
        let list = [1, 2, 3]
        if (list.indexOf(this.pageName) > -1 && !this.form.code)
          return this.$message({ message: translateTitle('Dams.ApplicationInterface.请将数据填写完毕'), type: 'error' })
        let obj = {}
        if (this.tabsIndex == 1) {
          obj = this.setSelectParam({ USER_ID: this.ChoiceObj.ID, ORG_ID: this.form.ORG_ID }, 'WAREHOUSE_ID')
        } else if (this.pageName == 'UserRole') {
          obj = {
            USER_ID: this.ChoiceObj.ID,
            USER_ROLE_ID: this.newRole,
          }
        } else if (this.tabsIndex == 2) {
          obj = this.setSelectParam({ USER_ID: this.ChoiceObj.ID, ORG_ID: this.form.ORG_ID }, 'OWNER_ID')
        } else if (this.tabsIndex == 3) {
          obj = this.setCascaderParam(this.ChoiceObj.ID, this.form.ORG_ID)
        } else if (this.tabsIndex == 0) {
          obj = {
            USER_ID: this.ChoiceObj.ID,
            USER_ROLE_ID: this.newRole,
          }
        }
        getList(this.url, {
          method: this.tabsList[this.tabsIndex].pageSetting.children.addMethod,
          data: JSON.stringify(obj),
        }).then((res) => {
          this.newAddDialog = false
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            this.query({ USER_ID: this.ChoiceObj.USER_ID }, this.tabsList[this.tabsIndex].pageSetting.children.search.form.method)
            this.form = {}
          }
        })
      },
      windowResize: debounce(function () {
        console.log('document.documentElement.clientHeight', document.documentElement.clientHeight)
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      async onSubmit(p) {
        let sub = JSON.parse(JSON.stringify(p))
        let obj = {}
        obj = {
          '#LIMIT#': this.mainTable.limit,
          '#PAGE_SIZE#': this.mainTable.pageSize,
          ...sub[0],
        }
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        if (this.tabsList[0].pageSetting.search) {
          let res = await getList(url, {
            data: JSON.stringify(obj),
            method: this.tabsList[0].pageSetting.search.form.method,
          })
          this.mainTable.tableList = res.data[this.tabsList[0].pageSetting.search.form.method].data
          this.mainTable.count = res.data[this.tabsList[0].pageSetting.search.form.method].count
        }
      },
      eventInit() {
        this.$sub(`userAuthorization_Table_singleClick_userAuthorization`, (page_arr) => {
          console.log('page_arr', page_arr[0])
          this.ChoiceObj = page_arr[0]
          this.secondOpen = true
          this.query({ USER_ID: this.ChoiceObj.USER_ID }, this.tabsList[this.tabsIndex].pageSetting.children.search.form.method)
        })
        this.unsubs.push(`userAuthorization_Table_singleClick_userAuthorization`)
        this.$sub(`userAuthorization_forms_on_search`, (data_arr) => {
          console.log('page_arr', data_arr[0])
          this.mainTable.limit = 1
          this.subForm = data_arr
          this.onSubmit(data_arr)
        })
        this.unsubs.push(`userAuthorization_forms_on_search`)
        this.$sub(`userAuthorization_Table_on_userAuthorization`, (page_arr) => {
          this.mainTable.limit = page_arr[0].limit
          this.mainTable.pageSize = page_arr[0].pageSize
          this.onSubmit(this.subForm)
        })
        this.unsubs.push(`userAuthorization_Table_on_userAuthorization`)
        this.tabsList.forEach((row) => {
          this.$sub(`${row.childrenTab.name}_Table_delBtn_${row.childrenTab.name}`, (page_arr) => {
            console.log(page_arr)
            this.$confirm(translateTitle('Dams.ApplicationInterface.确定删除'), translateTitle('Dams.ApplicationInterface.提示'), {
              confirmButtonText: translateTitle('Dams.ApplicationInterface.确定'),
              cancelButtonText: translateTitle('Dams.ApplicationInterface.取消'),
              type: 'warning',
            }).then(() => {
              this.delFuc(page_arr)
            })
          })
          this.unsubs.push(`${row.childrenTab.name}_Table_delBtn_${row.childrenTab.name}`)
        })
      },
      delFuc(page_arr) {
        console.log(this.pageName, page_arr)
        let obj = {}
        if (this.tabsIndex == 1) {
          obj = {
            USER_ID: this.ChoiceObj.ID,
            WAREHOUSE_ID: page_arr[0].WAREHOUSE_ID,
            ORG_CODE: page_arr[0].ORG_CODE,
          }
        } else if (this.tabsIndex == 0) {
          if (this.pageName == 'UserRole') {
            obj = {
              USER_ID: this.ChoiceObj.ID,
              USER_ROLE_ID: page_arr[0].USER_ROLE_ID,
            }
          } else {
            obj = {
              USER_ID: this.ChoiceObj.ID,
              ROLE_ID: page_arr[0].ROLE_ID,
            }
          }
        } else if (this.tabsIndex == 2) {
          obj = {
            USER_ID: this.ChoiceObj.ID,
            OWNER_ID: page_arr[0].OWNER_ID,
          }
        } else if (this.tabsIndex == 3) {
          obj = {
            ORG_ID: page_arr[0].ORG_ID,
            USER_ID: this.ChoiceObj.ID,
            ORDER_BUSINESS_TYPE: page_arr[0].BUSINESS_TYPE,
            ORDER_TYPE: page_arr[0].ORDER_TYPE,
          }
        }
        getList(this.url, {
          method: this.tabsList[this.tabsIndex].pageSetting.children.deleteMethod,
          data: JSON.stringify(obj),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            this.query({ USER_ID: this.ChoiceObj.USER_ID }, this.tabsList[this.tabsIndex].pageSetting.children.search.form.method)
          }
        })
      },
      init() {
        this.windowResize()
        if (this.tables && JSON.stringify(this.tables) != '{}') this.mainTable = this.tables
        this.configSetting = GFCD(this.subSystem.toLocaleLowerCase())
        this.url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        this.tabsList = this.authorizationList
        this.activeName = this.tabsList[0].name
        this.tabsIndex = this.tabsList.findIndex((el) => el.name == this.activeName)
        this.pageSetting = this.tabsList[this.tabsIndex].pageSetting
        if (this.pageName != 'WmsUserWarehouse' && this.pageName != 'WmsUsercargoOwner' && this.pageName != 'WmsUserReceipts') {
          this.query({ '#LIMIT#': 1, '#PAGE_SIZE#': 5000 }, this.optionMethod)
        }
        this.eventInit()
        this.getOrg()
      },
      async getOrg() {
        let url = GFCD('dams')
        let res = await getList(`${url.domain}${url.baseUrl}`, {
          data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }),
          method: 'dams.authorizationOrganization.query',
        })
        this.organizationOptions = res.data['dams.authorizationOrganization.query'].data
      },
      // 查询接口
      query(dataInfo, method) {
        console.log(this.tabsList, this.tabsIndex)
        if (method == this.tabsList[this.tabsIndex].pageSetting.children.search.form.method) {
          this.rightLodaing = true
        }
        getList(this.url, {
          method: method,
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 50,
            ...dataInfo,
          }),
        }).then((res) => {
          if (method == this.tabsList[this.tabsIndex].pageSetting.children.search.form.method) {
            console.log('res查询接口', res)
            this.rightLodaing = false
            let index = this.tabsList.findIndex((el) => el.name == this.activeName)
            console.log(index)
            if (index != undefined) {
              this.tabsList[index].childrenTab.tableList = res.data[method].data
            }
            // this.getChildrenTab.tableList = res.data[method].data
            console.log(this.tabsList)
          } else if (method == this.optionMethod) {
            // let userRoleList = ['WmsUserRole', 'LpmsUserRole', 'LwmsUserRole', 'LesUserRole', 'WcsUserRole']
            this.roleOptions = res.data[method].data
            if (this.tabsIndex == 1) {
              this.roleOptions.forEach((row) => {
                row.id = row.WAREHOUSE_ID
                row.label = row.WAREHOUSE_NAME
              })
            } else if (this.tabsIndex == 0) {
              if (this.pageName == 'UserRole') {
                this.roleOptions.forEach((row) => {
                  row.id = row.ID
                  row.label = row.ROLE_DESC
                })
              } else {
                this.roleOptions.forEach((row) => {
                  row.id = row.ROLE_ID
                  row.label = row.ROLE_NAME
                })
              }
            } else if (this.tabsIndex == 2) {
              this.roleOptions.forEach((row) => {
                row.id = row.OWNER_ID
                row.label = row.DESCRC
              })
            } else if (this.tabsIndex == 3) {
              this.roleOptions.forEach((row) => {
                row.id = row.CODE + ',' + row.CODE_ID
                row.label = row.CODE_NAMEC
              })
            }
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/ve/styles/elements.scss';
  :deep() {
    .el-cascader {
      width: 22%;
    }
    .el-form-item__content {
      width: 133px;
    }
    .el-form-item__label {
      padding: 0;
    }
    .el-input__inner {
      height: 26px;
      line-height: 26px;
      border-radius: 2px;
      padding: 0 6px;
    }
    .el-form-item--small.el-form-item {
      margin-bottom: 10px;
    }
    .el-form-item__label {
      margin-top: 0 !important;
    }
  }
</style>
